<?php

namespace app\admin\controller;

use app\admin\exception\AdminException;
use app\common\entity\Export;
use think\Db;
use think\Request;
use app\common\entity\User;
use app\common\entity\GoodsCategory;
use app\common\shop\ShopGoodsModel;

class Shop extends Admin
{

    /**
     * @power 内容管理|商品管理
     * @rank 0
     */
    public function index()
    {
        $categoryId = input('get.type');
        $goodsModel = new \app\common\entity\Goods();
        //商品列表
        $goodsLists = $goodsModel->getGoodsPages($categoryId);

        return $this->render('index', [
            'goodsLists' => $goodsLists,
            'model' => $goodsModel,
            'categoryModel'=>new GoodsCategory(),
            'cate' => \app\common\entity\GoodsCategory::getAllCate(),
        ]);
    }

     /**
     * @power 内容管理|商品管理@添加商品
     */
    public function create()
    {
        return $this->render('edit', [
            'cate' => \app\common\entity\GoodsCategory::getAllCate(),
            'model' => new \app\common\entity\Goods(),
            'ppk' => Db::name('ppk')->order('id desc')->select(),
            // 'levelcate' => \app\common\entity\UserPackage::getAllCate(),

        ]);
    }

    /**
     * @power 内容管理|商品管理@编辑商品
     */
    public function edit($id)
    {
        $data = Db::name('goods')->where('id', $id)->find();
        $data['goods_pic'] = json_decode($data['goods_pic']);
//        dump($data);die;
        if (!$data) {
            $this->error('用户对象不存在');
        }
        $data['ppk'] = $data['ppv'] = $data['pps'] = [];

        $data['pps'] = Db::name('GoodsPps')->where('gid', $data['id'])->select();
        $gvids = array_column($data['pps'], 'key');
        if (!empty($gvids)) $gvids = array_filter(array_flip(array_flip(explode('_', implode('_', $gvids)))));
        $pps = empty($gvids) ? [] : Db::name('GoodsPpv')->whereIn('id', $gvids)->column('id,gkid,ppv');
        foreach ($pps as $v) {
            $data['ppv'][$v['gkid']][$v['id']] = $v['ppv'];
        }
        if ($data['ppv']) {
            $data['ppk'] = Db::name('GoodsPpk')->whereIn('id', array_keys($data['ppv']))->column('id,ppk');
        }
        $data['ppsks'] = [];
        foreach ($data['ppk'] as $k => $v) {
            if (empty($data['ppv'][$k])) continue;

            $data['ppsks'][] = $v . '|_|' . implode('|_|', $data['ppv'][$k]);
        }
        $data['ppsks'] = implode('|||', $data['ppsks']);
        $data['pptable'] = [];
        $data['pptabdata'] = [];
        foreach ($data['pps'] as $v) {
            $keys = explode('_', $v['key']);
            $ks = [];
            foreach ($keys as $vv) {
                $ks[] = $pps[$vv]['ppv'];
            }
            $data['pptable'][] = implode('|_|', $ks);
            $data['pptabdata'][] = $v;
        }
        $data['pptable'] = json_encode($data['pptable']);
        $data['pptabdata'] = json_encode($data['pptabdata']);
//        dump($data);die;
        return $this->render('edit', [
            'info' => $data,
            'data' => $data,
            'ppk' => Db::name('ppk')->order('id desc')->select(),
            'cate' => \app\common\entity\GoodsCategory::getAllCate(),
            'model' => new \app\common\entity\Goods(),
            //'levelcate' => \app\common\entity\UserPackage::getAllCate(),

        ]);
    }

    /**
     * @power 内容管理|商品管理@添加商品
     */
    public function save(Request $request)
    {
//        var_dump($request->post());die;
        $res = $this->validate($request->post(), 'app\admin\validate\Goods');

        if (true !== $res) {
            return json()->data(['code' => 1, 'message' => $res]);
        }
        $data = $request->post();
        $ppsks = $pps = [];
        if ($data['is_pp'] = $request->param('ispps', 0, 'intval')) {
            if (!(($ppsks = $request->param('ppsks', '', 'trim')) && ($ppsks = explode('|||', $ppsks)))) return json()->data(['code' => 1, 'message' => '无效属性']);
            if (!($pps = $request->param('pps/a', []))) return json()->data(['code' => 1, 'message' => '无效属性']);

            $noPps = true;
            foreach ($pps as $v) {
                if (intval($v['stock']) < 1) continue;
//                    if(!is_numeric($v['price']) || $v['price']<=0 || intval($v['stock'])<1) continue;
                $noPps = false;
                break;
            }
            if ($noPps) return json()->data(['code' => 1, 'message' => '请设置属性价格与库存']);
        } else {
            $data['goods_num'] = $request->param('goods_num', 0, 'intval');
        }

        $service = new \app\common\entity\Goods();
        $result = $service->addGoods($data);

        if (!$result) {
            throw new AdminException('保存失败');
        }
        $res = $this->pps($data['is_pp'], $result, $ppsks, $pps);
        //添加用户提醒
//        if ($request->post('category') == 1 && $request->post('status') == 1) {
//            User::update(['notice' => 1], ['notice' => 0]);
//        }

        return json(['code' => 0, 'toUrl' => url('/admin/shop')]);
    }

    /**
     * @power 内容管理|商品管理@编辑商品
     */
    public function update(Request $request, $id)
    {

        $res = $this->validate($request->post(), 'app\admin\validate\Goods');

        if (true !== $res) {
            return json()->data(['code' => 1, 'message' => $res]);
        }


        $entity = $this->checkInfo($id);

        $service = new \app\common\entity\Goods();

        $data = $request->post();
        $ppsks = $pps = [];
        if ($data['is_pp'] = $request->param('ispps', 0, 'intval')) {
            if (!(($ppsks = $request->param('ppsks', '', 'trim')) && ($ppsks = explode('|||', $ppsks)))) return json()->data(['code' => 1, 'message' => '无效属性']);
            if (!($pps = $request->param('pps/a', []))) return json()->data(['code' => 1, 'message' => '无效属性']);

            $noPps = true;
            foreach ($pps as $v) {
                if (intval($v['stock']) < 1) continue;
//                    if(!is_numeric($v['price']) || $v['price']<=0 || intval($v['stock'])<1) continue;
                $noPps = false;
                break;
            }
            if ($noPps) return json()->data(['code' => 1, 'message' => '请设置属性价格与库存']);
        } else {
            $data['goods_num'] = $request->param('goods_num', 0, 'intval');
        }

        $res = $this->pps($data['is_pp'], $id, $ppsks, $pps);
        $result = $service->updateGoods($entity, $data);

        if (!$result) {
            // throw new AdminException('保存失败');
        }

        return json(['code' => 0, 'toUrl' => url('/admin/shop')]);
    }


    /**
     * @power 内容管理|商品管理@删除商品
     */
    public function delete(Request $request, $id)
    {
        $entity = $this->checkInfo($id);

        if (!$entity->delete()) {
            throw new AdminException('删除失败');
        }

        return json(['code' => 0, 'message' => 'success']);
    }

    private function checkInfo($id)
    {
        $entity = \app\common\entity\Goods::where('id', $id)->find();
        if (!$entity) {
            throw new AdminException('对象不存在');
        }

        return $entity;
    }

    /**
     * @power 内容管理|商品管理@添加商品分类
     */
    public function createCategory()
    {
        return $this->render('category', [
            'cate' => \app\common\entity\Goods::getAllCate()
        ]);
    }

    /**
     * @power 内容管理|商品管理@添加商品分类
     */
    public function categorySave(Request $request)
    {
        $res = $this->validate($request->post(), 'app\admin\validate\CategoryForm');

        if (true !== $res) {
            return json()->data(['code' => 1, 'message' => $res]);
        }

        $service = new \app\common\entity\GoodsCategory();
        $result = $service->addGoodsCategoryParent($request->post());


        if (!$result) {
            throw new AdminException('保存失败');
        }

        return json(['code' => 0, 'toUrl' => url('/admin/shop')]);
    }

    private function pps($is_pp, $gid, $ppsks, $pps)
    {
        Db::name('GoodsPpk')->where('gid', $gid)->delete();
        Db::name('GoodsPpk')->where('gid', $gid)->delete();
        Db::name('GoodsPps')->where('gid', $gid)->delete();
        if (empty($is_pp)) return;
        $datav = [];
        foreach ($ppsks as $v) {
            $ppk = explode('|_|', $v);
            $cc = count($ppk);
            if ($cc < 2) return;
            $kid = Db::name('GoodsPpk')->insertGetId([
                'gid' => $gid,
                'ppk' => $ppk[0],
            ]);
            if (empty($kid)) return;
            for ($i = 1; $i < $cc; $i++) {
                $datav[] = [
                    'gid' => $gid,
                    'gkid' => $kid,
                    'ppv' => $ppk[$i],
                ];
            }
        }
        if ($datav) Db::name('GoodsPpv')->insertAll($datav);

        $ppks = Db::name('GoodsPpk')->where('gid', $gid)->order('id')->column('id');

        $ppvs = [];
        $rs = Db::name('GoodsPpv')->where('gid', $gid)->order('id')->select();
        foreach ($rs as $v) {
            $ppvs[$v['gkid']][$v['ppv']] = $v['id'];
        }

        $data = [];
        foreach ($pps as $k => $v) {
//            if(!is_numeric($v['price'])) continue;
            $stock = intval($v['stock']);
            if ($stock < 1) continue;

            $point = !empty($v['point']) && is_numeric($v['point']) ? $v['point'] : 0;

            $ks = explode('|_|', $k);
            if (count($ks) != count($ppks)) continue;
            $key = [];
            foreach ($ks as $k2 => $v2) {
                $vv2 = $ppvs[$ppks[$k2]][$v2];
                if (empty($vv2)) continue;
                $key[] = $vv2;
            }
            if (count($key) != count($ppks)) continue;
            $data[] = [
                'gid' => $gid,
                'key' => implode('_', $key),
                'price' => empty($v['price']) ? 0 : $v['price'],
                'point' => $point,
                'stock' => $stock,
            ];
        }
        if ($data) return Db::name('GoodsPps')->insertAll($data);
    }

    function ppk()
    {
        $res = Db::name('ppk')->order('id desc')->select();
        return $this->toData($res);
    }

    function ppkadd(Request $request)
    {
        $val = $request->param('val', '', 'trim');
        $m = Db::name('ppk');
        if (!($id = $m->where('ppk', $val)->value('id'))) {
            $id = Db::name('ppk')->insertGetId([
                'ppk' => $val
            ]);
        }

        return $this->toData([
            'id' => $id
        ]);
    }

    function ppv(Request $request)
    {
        $id = $request->param('id', 0, 'intval');
        if (!db('ppk')->where('id', $id)->count()) return $this->toUrl();
        return $this->toData(Db::name('ppv')->where('kid', $id)->order('id desc')->select());
    }

    function ppkdel(Request $request)
    {
        $id = $request->param('id', '', 'trim');
        if (db('ppv')->where('kid', $id)->count()) return $this->toMsg('请先删除此类型的所有属性值');

        db('ppk')->where('id', $id)->delete();
        return $this->toUrl();
    }

    function ppvadd(Request $request)
    {
        $id = $request->param('id', 0, 'intval');
        $val = $request->param('val', '', 'trim');
        if (empty($val)) return;
        $m = Db::name('ppv');
        $data = [
            'kid' => $id,
            'ppv' => $val
        ];
        if ($id = $m->where($data)->value('id'))
            return $this->toData([
                'id' => $id
            ]);

        $id = Db::name('ppv')->insertGetId($data);
        return $this->toData([
            'id' => $id
        ]);
    }

    function ppvdel(Request $request)
    {
        $id = $request->param('id', 0, 'intval');
        $m = Db::name('ppv');
        if (!($kid = $m->where('id', $id)->value('kid'))) return;
        $m->where('id', $id)->delete();
//        if(!($m->where('kid', $kid)->count())) {
//            Db::name('ppk')->where('id', $kid)->delete();
//        }
    }

    protected function toMsg($msg) {
        return ['code' => 1, 'msg' => $msg];
    }
    protected function toData($data)
    {
        return ['code' => 1, 'data' => $data];
    }

    protected function toUrl($url = '', $msg = '')
    {
        $data = ['code' => 0, 'toUrl' => $url];
        if (!empty($data)) $data['msg'] = $msg;
        return $data;
    }


}
